const express = require('express')
// var moment = require("moment");             //JavaScript 日期处理类库
const router = express.Router()
router.get('/', function (req, res) {
    res.send('hello, express')
})

router.get('/currenttime', function (req, res) {
    let severlocalTime = moment().locale('zh-cn').format('YYYY-MM-DD HH:mm:ss');
    res.send(severlocalTime);
})

//登录校验
router.post("/checkpassip", function (req, res) {
    var CurrIP = req.connection.remoteAddress;  //当前IP
    console.log("CurrIP: " + CurrIP);
    var param = req.body;                       //请求主体
    var paramObj = JSON.parse(param.storObj);   //请求主体的对象
    console.log("param：" + param);
    console.log("paramObj： " + paramObj);
    //拿到对象才能继续操作
    // if (param.storObj) {
    //     paramObj = 
    // }

    if (param != "") {//请求数据不为空
        //查询账号密码
        db.all("select * from tb_stdInfo where stuID=? and pwd=?", [param.user, param.pwd], function (err, data) {
            //查询成功，返回对象
            if (!err && data.length != 0) {
                if (data[0]) {

                }
                var bs = new Buffer.from(JSON.stringify(data[0]), "UTF-8");
                rtn = {
                    msg: bs.toString("base64"),
                    flag: "TRUE",
                    storObj: {
                        flag: "INFO",
                        stuData: {
                            stuID: param.user,
                            CurrIp: CurrIP
                        }
                    }
                };

            }

            //查询不成功
            res.send({
                rtnFlag: "FAILED",               //rtn的状态
                msg: "账号或者密码错误",          //返回的信息
                storObj: {                      //仓库对象 返回的数据
                    flag: "EMPTY",              //数据的状态
                    stuID: "",                  //登录ID
                    CurrIp: ""                  //当前登录IP
                }
            });
        })
    } else {//请求数据为空
        res.send({
            rtnFlag: "EMPTY",    //rtn的状态
            msg: "请求数据为空",            //返回的信息
            storObj: {              //仓库对象 返回的数据
                flag: "EMPTY",       //数据的状态
                stuID: "",          //登录ID
                CurrIp: ""          //当前登录IP
            }
        })
    }



    //前台缓存被清了
    if (param.storObj == "") {
        //console.log("null")

        //再查一遍数据库；
        db.all("select * from tb_Online where CurrIP=?", [CurrIP], function (err, data) {
            //能查出来学号；
            if (!err && data.length != 0) {
                console.log(data[0]);
                //查出来的学号跟登陆的学号不一样
                if (data[0].stuID != param.user) {
                    //查询状态
                    db.all("select * from tb_Stustat where stuID = ?", [param.user], function (err, data1) {
                        if (!err && data1.length != 0) {
                            //标记为一表示可以修改ip对应的学号
                            if (data1[0].flag == '1') {
                                //验证账号密码
                                db.all("select * from tb_stdInfo where stuID=? and pwd=?", [param.user, param.pwd], function (err, data2) {
                                    //验证通过返回对象
                                    if (!err && data2.length != 0) {
                                        var bs = new Buffer.from(JSON.stringify(data2[0]), "UTF-8");
                                        var rtn = {
                                            msg: bs.toString("base64"),
                                            flag: "T",
                                            storObj: {
                                                flag: "INFO",
                                                stuData: {
                                                    stuID: param.user,
                                                    CurrIp: CurrIP
                                                }
                                            }
                                        };
                                        //把电脑IP对应学号改为现在登陆的人的学号；
                                        db.all("update tb_Online set stuID = ? where CurrIP=?", [param.user, CurrIP], function (err, data3) {
                                            if (!err) {
                                                res.send(rtn);
                                            }
                                            else {
                                                res.send({ msg: "failed" });
                                            }
                                        })
                                    }
                                    //验证未通过
                                    else {
                                        res.send({ msg: "failed" });
                                    }
                                })
                            }
                        }
                        else {
                            //直接返回错误 二次登陆
                            res.send({ msg: "failed1" })
                        }
                    })

                }
                //查出来的学号和登陆的一样
                else {
                    //登陆验证
                    db.all("select * from tb_stdInfo where stuID=? and pwd=?", [param.user, param.pwd], function (err, data1) {
                        //验证通过返回对象
                        if (!err && data1.length != 0) {
                            var bs = new Buffer.from(JSON.stringify(data1[0]), "UTF-8");
                            var rtn = {
                                msg: bs.toString("base64"),
                                flag: "T",
                                storObj: {
                                    flag: "INFO",
                                    stuData: {
                                        stuID: param.user,
                                        CurrIp: CurrIP
                                    }
                                }
                            };
                            res.send(rtn);
                            console.log("【" + data1[0].stuID + "-" + data1[0].stuName + "】 登录...");
                        }
                        //验证未通过
                        else {
                            res.send({ msg: "failed" });
                        }
                    })
                }
            }
            //查询没问题而且没数据就证明没被占用；
            else if (!err) {
                //验证登陆
                db.all("select * from tb_stdInfo where stuID=? and pwd=?", [param.user, param.pwd], function (err, data) {
                    if (!err && data.length != 0) {
                        var bs = new Buffer.from(JSON.stringify(data[0]), "UTF-8");
                        var rtn = {
                            msg: bs.toString("base64"),
                            flag: "T",
                            storObj: {
                                flag: "INFO",
                                stuData: {
                                    stuID: param.user,
                                    CurrIp: CurrIP
                                }
                            }
                        };
                        //只有插入成功才可以返回数据；
                        db.all("INSERT INTO tb_Online (stuID, CurrIP,starttime) VALUES (?,?,?)", [param.user, CurrIP, severStartTime], function (err, data2) {
                            //插入成功返回给用户；
                            if (!err) {
                                res.send(rtn);
                                console.log("【" + data[0].stuID + "-" + data[0].stuName + "】 登录...");
                            }
                            else {
                                res.send({ msg: "failed1" });
                            }
                        })
                    }
                    else {
                        res.send({ msg: "failed" });
                    }
                })
            }
            //查询失败；
            else {
                res.send({ msg: "failed" });
            }
        })
    }
    //storObj为空，证明该IP并未被占用；
    else if (paramObj.flag == "EMPTY") {

        // console.log("EMPTY")
        //验证登陆
        db.all("select * from tb_stdInfo where stuID=? and pwd=?", [param.user, param.pwd], function (err, data) {
            if (!err && data.length != 0) {
                var bs = new Buffer.from(JSON.stringify(data[0]), 'utf8');
                var rtn = {
                    msg: bs.toString("base64"),
                    flag: "T",
                    storObj: {
                        flag: "INFO",
                        stuData: {
                            stuID: param.user,
                            CurrIp: CurrIP
                        }
                    }
                };
                //只有插入成功才可以返回数据；
                db.all("INSERT INTO tb_Online (stuID, CurrIP,starttime) VALUES (?,?,?)", [param.user, CurrIP, severStartTime], function (err, data2) {
                    //插入成功返回给用户；
                    if (!err) {
                        res.send(rtn);
                        console.log("【" + data[0].stuID + "-" + data[0].stuName + "】 登录...");
                    }
                    else {
                        res.send({ msg: "failed1" });
                    }
                })
            }
            //登陆失败
            else {
                res.send({ msg: "failed" });
            }
        })
    }
    //有数据，证明IP被登陆过，需要验证登陆的学号和占用的学号，相同继续验证登陆，不相同就返回错误信息；
    else if (paramObj.flag == "INFO") {
        //判断学号和登陆的学号不一样 
        if (param.user != paramObj.stuData.stuID) {
            //判断此时登陆的学号是否有修改权限
            db.all("select * from tb_Stustat where stuID = ?", [param.user], function (err, data1) {
                //查询到有数据
                if (!err && data1.length != 0) {
                    //标记为1 表示可以修改ip对应的学号

                    if (data1[0].flag == '1') {
                        //验证登陆
                        db.all("select * from tb_stdInfo where stuID=? and pwd=?", [param.user, param.pwd], function (err, data2) {
                            //验证通过返回对象
                            if (!err && data2.length != 0) {
                                var bs = new Buffer.from(JSON.stringify(data2[0]), "UTF-8");
                                var rtn = {
                                    msg: bs.toString("base64"),
                                    flag: "T",
                                    storObj: {
                                        flag: "INFO",
                                        stuData: {
                                            stuID: param.user,
                                            CurrIp: CurrIP
                                        }
                                    }
                                };
                                //更新此时表中IP对应的学号
                                db.all("update tb_Online set stuID = ? where CurrIP=?", [param.user, CurrIP], function (err, data3) {
                                    if (!err) {
                                        res.send(rtn);
                                    }
                                    else {
                                        res.send({ msg: "failed" });
                                    }
                                })
                            }
                            //验证未通过
                            else {
                                res.send({ msg: "failed" });
                            }
                        })
                    }
                    //返回二次登陆
                    else {
                        res.send({ msg: "failed1" });
                    }
                }
                else {
                    //直接返回错误 二次登陆
                    res.send({ msg: "failed1" })
                }
            })
        }
        //学号一样
        else {
            db.all("select * from tb_stdInfo where stuID=? and pwd=?", [param.user, param.pwd], function (err, data1) {
                //验证通过返回对象
                if (!err && data1.length != 0) {
                    var bs = new Buffer.from(JSON.stringify(data1[0]), "UTF-8");
                    var rtn = {
                        msg: bs.toString("base64"),
                        flag: "T",
                        storObj: {
                            flag: "INFO",
                            stuData: {
                                stuID: param.user,
                                CurrIp: CurrIP
                            }
                        }
                    };
                    res.send(rtn);
                    console.log("【" + data1[0].stuID + "-" + data1[0].stuName + "】 登录...");
                }
                //验证未通过
                else {
                    res.send({ msg: "failed" });
                }
            })
        }
    }
    //比较失败；
    else {
        res.send({ msg: "failed" });
    }
});


module.exports = router